#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include "wrap.h"
int main(int argc, char const *argv[])
{
        int lfd = Socket(AF_LOCAL,SOCK_STREAM,0);

        //如果套接字文件存在，删除套接字文件 否则下次启动程序会bind error: Address already in use
        unlink("server.sock");
        
        //绑定
        struct sockaddr_un serv;
        serv.sun_family = AF_LOCAL;
        strcpy(serv.sun_path,"server.sock");
        Bind(lfd,(struct sockaddr *)&serv,sizeof(serv));

        //监听
        Listen(lfd,128);

        //等待接收连接请求
        struct sockaddr_un client;
        memset(&client, 0, sizeof(client));
        socklen_t client_len = sizeof(client);
        int cfd = Accept(lfd,(struct sockaddr*)&client, &client_len);
        printf("client bind file:%s\n",client.sun_path);

        //通讯
        char buf[1024] = {0};
        while (1){
                memset(buf,0,sizeof(buf));
                int recvlen = recv(cfd,buf,sizeof( buf),0);
                if(recvlen == -1){
                        perr_exit("recv error");
                }else if(recvlen == 0){
                        printf("客户端主动关闭连接\n");
                        Close(cfd);
                        break;
                }else{
                        printf("recv buf:%s\n",buf);
                        send(cfd,buf,recvlen,0);
                }
        }
        Close(cfd);
        Close(lfd);
        return 0;
}
